﻿using C1.Win.C1FlexGrid;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using TableJsonHelper;
using YNCNumberSys.db;
using YNCNumberSys.DbDal;
using YNCNumberSys.Entity;
using cadApp = Autodesk.AutoCAD.ApplicationServices.Application;
namespace YNCNumberSys
{
    /// <summary>
    /// 只有2处，内部调用事务了，XSL 核查一遍20221121
    /// </summary>
    public partial class ApplyOut : Form
    {
        private string s_用户名;
        public string str_用户名
        {
            get { return s_用户名; }
            set
            {
                s_用户名 = value;
                this.tbx_用户名.Text = value;
            }
        }
        private System.Data.DataTable dt_编码位数;
        CommandManager commandManager = new CommandManager();
        ConnectionManager connectionManager = new ConnectionManager();

        public ApplyOut()
        {
            InitializeComponent();
            string sql = "select * from 编码位数 where 1=1";
            dt_编码位数 = commandManager.ExecuteNonQuery(connectionManager.getConnection(), sql, "编码位数");
        }
        bool m_lockA号 = false;
        private void ApplyOut_Load(object sender, EventArgs e)
        {
            tbx_设计日期.Text = System.DateTime.Now.ToString("yyyy-MM-dd");

            InitDal dal = new InitDal();
            DataTable dt0=dal.GetIninitEmptyDatable();
            m_flex.DataSource = dt0;
            m_flex.AutoSizeRows();
            m_flex.AutoSizeCols();
            try
            {
                m_lockA号 = true;
                PaperCodeDal paperCodeDal = new PaperCodeDal();
                DataTable dt1 = paperCodeDal.GetDistinctJCXH();
                cbx_机床型号.DisplayMember = "机床型号";
                var dr = dt1.NewRow();
                dr["机床型号"] = "";
                dt1.Rows.InsertAt(dr, 0);
                cbx_机床型号.BeginUpdate();
                cbx_机床型号.DataSource = dt1;
                cbx_机床型号.EndUpdate();
                DataTable dt2 = paperCodeDal.GetDistinctWXDW();
                cbx_外协单位.DisplayMember = "外协单位";
                var dr2 = dt2.NewRow();
                dr2["外协单位"] = "";
                dt2.Rows.InsertAt(dr2, 0);
                cbx_外协单位.DataSource = dt2;
            }
            catch
            {

            }
            finally
            {
                cbx_机床型号.SelectedIndex = -1;
                m_lockA号 = false;
            }
        }

        //private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        //{

        //}

        private void btn_确定_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.cbx_外协单位.Text))
            {
                cadApp.ShowAlertDialog("外协单位不能为空！");
                return;
            }
            if (string.IsNullOrEmpty(this.cbx_机床型号.Text))
            {
                cadApp.ShowAlertDialog("机床型号不能为空！");
                return;
            }
            if (string.IsNullOrEmpty(this.cbx_A号.Text))
            {
                cadApp.ShowAlertDialog("A号不能为空！");
                return;
            }

            wxApl wxapl = new wxApl();
            
            DataTable dt = (DataTable)m_flex.DataSource;
            List<string> lst = new List<string>();
            if (dt.Rows.Count > 0)
            {
                foreach (DataColumn dc in dt.Columns)
                {
                    string cap = dc.ColumnName;
                    int count = (int)m_flex[1, cap];
                    if (count > 0)
                    {
                        string sql = string.Format(@"INSERT INTO [YNCNumberSys].[dbo].[WxPapercodeTemp]([Serial],[Length]) VALUES('{0}',{1});", cap, count);
                        lst.Add(sql);
                    }
                }
            }
            if(lst.Count==0)return;
            StatusDal statusDal = new StatusDal();
            string isLock = statusDal.IsLock(s_用户名);
            if (isLock != "ok")
            {
                cadApp.ShowAlertDialog(isLock);
                return;
            }
            else
            {
                DataTable dtLock = statusDal.Lock(s_用户名);
                if (dtLock.Rows.Count == 1)
                {
                    if ((string)dtLock.Rows[0]["user"] == s_用户名)
                    {
                        wxapl.BuildWxPaperCode(lst);
                        DateTime t1 = DateTime.Now;
                        DataTable dtCheck = wxapl.CheckFileNo(this.cbx_机床型号.Text.Trim(), this.cbx_A号.Text.Trim(), s_用户名);
                        if (dtCheck.Rows.Count == 0)
                        {
                            t1 = DateTime.Now;
                            if (checkBoxIncreaseMax.Checked)
                                dt = wxapl.ExecuteStoredProcedureMaxIncrease(
                                        this.cbx_机床型号.Text.Trim(),
                                        this.cbx_A号.Text.Trim(),
                                        string.Empty,
                                        string.Empty,
                                        s_用户名,
                                        string.Empty,
                                        1,
                                        this.cbx_外协单位.Text.Trim());
                            else
                                dt = wxapl.ExecuteStoredProcedure(
                                        this.cbx_机床型号.Text.Trim(),
                                        this.cbx_A号.Text.Trim(),
                                        string.Empty,
                                        string.Empty,
                                        s_用户名,
                                        string.Empty,
                                        1,
                                        this.cbx_外协单位.Text.Trim());
                            dt.Columns.Add("图纸编号 ", typeof(string));
                            for (int k=0;k< dt.Rows.Count;k++)
                            {
                                dt.Rows[k]["图纸编号 "] = /*dt.Rows[k]["图纸类型"].ToString() +*/ dt.Rows[k]["图纸编号"].ToString().PadLeft(6,'0');
                            }
                            if(dt.Columns.Contains("图纸编号"))
                            {
                                dt.Columns.Remove(dt.Columns["图纸编号"]);
                            }
                            if (dt.Columns.Contains("名称"))    
                            {
                                dt.Columns.Remove(dt.Columns["名称"]);
                            }
                            if (dt.Columns.Contains("规格"))
                            {
                                dt.Columns.Remove(dt.Columns["规格"]);
                            }
                            if (dt.Columns.Contains("外协"))
                            {
                                dt.Columns.Remove(dt.Columns["外协"]);
                            }
                            if (dt.Columns.Contains("作废"))
                            {
                                dt.Columns.Remove(dt.Columns["作废"]);
                            }
                            m_flexResut.DataSource = dt;

                            if (dt != null)
                            {
                                DateTime t2 = DateTime.Now;
                                TimeSpan tPan = t2 - t1;
                                this.labelResult.Text = string.Format(@"耗时{0}h{1}m{2}.{3}s,",
                                    tPan.Hours, tPan.Minutes, tPan.Seconds, t1.Millisecond) + "共计:" + dt.Rows.Count + "条记录。";
                                this.labelCheck.Text = "共计:" + 0 + "条记录";
                                if (m_flexResut.Cols.Contains("ID"))
                                    m_flexResut.Cols["ID"].Visible = false;
                                if (m_flexResut.Cols.Contains("名称"))
                                    m_flexResut.Cols["名称"].Visible = false;
                                if (m_flexResut.Cols.Contains("规格"))
                                    m_flexResut.Cols["规格"].Visible = false;
                                if (m_flexResut.Cols.Contains("外协"))
                                    m_flexResut.Cols["外协"].Visible = false;
                                if (m_flexResut.Cols.Contains("外协单位"))
                                    m_flexResut.Cols["外协单位"].Visible = false;
                                if (m_flexResut.Cols.Contains("作废"))
                                    m_flexResut.Cols["作废"].Visible = false;
                                if (m_flexResut.Cols.Contains("图纸编号"))
                                    m_flexResut.Cols["图纸编号"].Visible = false;
                                tabPageResut.ImageIndex = 1;
                                for (int r = 1; r < m_flexResut.Rows.Count; r++)
                                {
                                    m_flexResut[r, 0] = r;
                                }
                            }
                            m_flexResut.AutoSizeCols();
                            m_flexResut.AutoSizeRows();
                            this.tabControl1.SelectedTab = this.tabPageResut;
                        }
                        else
                        {
                            m_flexCheck.DataSource = dtCheck;
                            DateTime t2 = DateTime.Now;
                            TimeSpan tPan = t2 - t1;
                            if (dtCheck != null)
                            {
                                this.labelCheck.Text = string.Format("耗时{0}h{1}m{2}.{3}s,", tPan.Hours, tPan.Minutes, tPan.Seconds, t1.Millisecond) + "共计:" + dtCheck.Rows.Count + "条记录。";
                                this.labelResult.Text = "共计:" + 0 + "条记录";
                                if (m_flexCheck.Cols.Contains("ID"))
                                    m_flexCheck.Cols["ID"].Visible = false;
                                if (m_flexCheck.Cols.Contains("名称"))
                                    m_flexCheck.Cols["名称"].Visible = false;
                                if (m_flexCheck.Cols.Contains("规格"))
                                    m_flexCheck.Cols["规格"].Visible = false;
                                if (m_flexCheck.Cols.Contains("外协"))
                                    m_flexCheck.Cols["外协"].Visible = false;
                                if (m_flexCheck.Cols.Contains("外协单位"))
                                    m_flexCheck.Cols["外协单位"].Visible = false;
                                if (m_flexCheck.Cols.Contains("作废"))
                                    m_flexCheck.Cols["作废"].Visible = false;
                                for (int r = 1; r < m_flexCheck.Rows.Count; r++)
                                {
                                    m_flexCheck[r, 0] = r;
                                }
                            }
                            m_flexCheck.AutoSizeCols();
                            m_flexCheck.AutoSizeRows();
                            this.tabControl1.SelectedTab = tabPageChk;
                            tabPageChk.ImageIndex = 0;

                        }
                    }
                }
                else
                {
                    tabPageChk.ImageIndex = -1;
                }
                statusDal.UnLock(s_用户名);
            }
            for (int r = 1; r < m_flex.Rows.Count; r++)
            {
                m_flex[r, 0] = r;
            }
            m_flex.AutoSizeCols();
            m_flex.AutoSizeRows();
        }

        private void cbx_机床型号_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (m_lockA号) return;
            cbx_A号.DataSource=null;
            if (cbx_机床型号.SelectedIndex == -1)
                cbx_A号.SelectedIndex = -1;
            string txtJCXN = cbx_机床型号.Text;
            PaperCodeDal paperCodeDal = new PaperCodeDal();
            DataTable dt=paperCodeDal.GetDistinctAH(txtJCXN);
            cbx_A号.DisplayMember = "A号";
            var dr = dt.NewRow();
            dr["A号"] = "";
            dt.Rows.InsertAt(dr, 0);
            cbx_A号.BeginUpdate();
            cbx_A号.DataSource = dt;
            cbx_A号.EndUpdate();
            cbx_A号.SelectedIndex = -1;
        }

        private void button导出Excel_Click(object sender, EventArgs e)
        {
            if (m_flexResut.DataSource != null)
            {
                if (((DataTable)m_flexResut.DataSource).Rows.Count >= 1)
                {
                    SaveFileDialog saveImageDialog = new SaveFileDialog();
                    saveImageDialog.Filter = "Excel Files (*.xls)|*.xls";
                    saveImageDialog.Title = @"导出图号分配结果";
                    saveImageDialog.FileName = DateTime.Now.ToString("yyMMdd_") + this.cbx_外协单位.Text.Trim() + "_" + this.cbx_机床型号.Text.Trim()+ this.cbx_A号.Text.Trim();
                    if (saveImageDialog.ShowDialog() == DialogResult.OK)
                    {
                        string savePath = saveImageDialog.FileName;
                        m_flexResut.SaveExcel(savePath, @"要号成功", FileFlags.IncludeFixedCells);
                    }
                }
            }
            if (m_flexCheck.DataSource != null)
            {
                if (((DataTable)m_flexCheck.DataSource).Rows.Count >= 1)
                {
                    SaveFileDialog saveImageDialog = new SaveFileDialog();
                    saveImageDialog.Filter = "Excel Files (*.xls)|*.xls";
                    saveImageDialog.Title = @"导出错误日志";
                    saveImageDialog.FileName = DateTime.Now.ToString("yyMMdd_") + this.cbx_外协单位.Text.Trim() + "_" + this.cbx_机床型号.Text.Trim() + this.cbx_A号.Text.Trim();
                    if (saveImageDialog.ShowDialog() == DialogResult.OK)
                    {
                        string savePath = saveImageDialog.FileName;
                        m_flexCheck.SaveExcel(savePath, @"要号错误", FileFlags.IncludeFixedCells);
                    }
                }
            }
        }

        
        #region 将json转换为DataTable
        /// <summary>
        /// 将json转换为DataTable
        /// </summary>
        /// <param name="strJson">得到的json</param>
        /// <returns></returns>
        private DataTable JsonToDataTable(string strJson)
        {
            //转换json格式
            strJson = strJson.Replace(",\"", "*\"").Replace("\":", "\"#").ToString();
            //取出表名  
            var rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase);
            string strName = rg.Match(strJson).Value;
            DataTable tb = null;
            //去除表名  
            strJson = strJson.Substring(strJson.IndexOf("[") + 1);
            strJson = strJson.Substring(0, strJson.IndexOf("]"));
            //获取数据  
            rg = new Regex(@"(?<={)[^}]+(?=})");
            MatchCollection mc = rg.Matches(strJson);
            for (int i = 0; i < mc.Count; i++)
            {
                string strRow = mc[i].Value;
                string[] strRows = strRow.Split('*');
                //创建表  
                if (tb == null)
                {
                    tb = new DataTable();
                    tb.TableName = strName;
                    foreach (string str in strRows)
                    {
                        var dc = new DataColumn();
                        string[] strCell = str.Split('#');
                        if (strCell[0].Substring(0, 1) == "\"")
                        {
                            int a = strCell[0].Length;
                            dc.ColumnName = strCell[0].Substring(1, a - 2);
                        }
                        else
                        {
                            dc.ColumnName = strCell[0];
                        }
                        tb.Columns.Add(dc);
                    }
                    tb.AcceptChanges();
                }
                //增加内容  
                DataRow dr = tb.NewRow();
                for (int r = 0; r < strRows.Length; r++)
                {
                    dr[r] = strRows[r].Split('#')[1].Trim().Replace("，", ",").Replace("：", ":").Replace("\"", "");
                }
                tb.Rows.Add(dr);
                tb.AcceptChanges();
            }
            return tb;
        }
        #endregion
        private void buttonExportJson_Click(object sender, EventArgs e)
        {
            if (m_flexResut.DataSource != null)
            {
                if (((DataTable)m_flexResut.DataSource).Rows.Count >= 1)
                {
                    SaveFileDialog saveImageDialog = new SaveFileDialog();
                    saveImageDialog.Filter = "Json Files (*.json)|*.json";
                    saveImageDialog.Title = @"导出图号分配结果";
                    saveImageDialog.FileName = DateTime.Now.ToString("yyMMdd_") + this.cbx_外协单位.Text.Trim() + "_" + this.cbx_机床型号.Text.Trim() + "_" + this.cbx_A号.Text.Trim() + "_Suc";
                    if (saveImageDialog.ShowDialog() == DialogResult.OK)
                    {
                        string savePath = saveImageDialog.FileName;
                        string s = DataTableAndJsonHelper.DataTableToJsonWithJsonNet((DataTable)m_flexResut.DataSource);
                        string sEnc = EnOrDeEncryptHelper.EncryptText(s);
                        File.WriteAllText(savePath, sEnc);
                    }
                }
            }
            else
            {
                if (m_flexCheck.DataSource != null)
                {
                    if (((DataTable)m_flexCheck.DataSource).Rows.Count >= 1)
                    {
                        SaveFileDialog saveImageDialog = new SaveFileDialog();
                        saveImageDialog.Filter = "Json Files (*.json)|*.json";
                        saveImageDialog.Title = @"导出错误日志";
                        saveImageDialog.FileName = DateTime.Now.ToString("yyMMdd_") + this.cbx_外协单位.Text.Trim() + "_" + this.cbx_机床型号.Text.Trim() + "_" + this.cbx_A号.Text.Trim() + "_Err";
                        if (saveImageDialog.ShowDialog() == DialogResult.OK)
                        {
                            string savePath = saveImageDialog.FileName;
                            string s = DataTableAndJsonHelper.DataTableToJsonWithJsonNet((DataTable)m_flexCheck.DataSource);
                            
                            File.WriteAllText(savePath, s);
                        }
                    }
                }
            }
        }

        private void buttonImportJson_Click(object sender, EventArgs e)
        {
            OpenFileDialog openDialog = new OpenFileDialog();
            openDialog.Filter = "Json Files (*.json)|*.json";
            openDialog.Title = @"导入日志";
            if (openDialog.ShowDialog() == DialogResult.OK)
            {
                string savePath = openDialog.FileName;
                string s=File.ReadAllText(savePath);
                DataTable dt = JsonToDataTable(s);
            }
        }

        private void buttonDefault_Click(object sender, EventArgs e)
        {
            DataTable dt = (DataTable)m_flex.DataSource;
            if (dt != null)
            {
                if (dt.Rows.Count != 1)
                {
                    InitDal dal = new InitDal();
                    dt = dal.GetIninitEmptyDatable();
                    m_flex.DataSource = dt;
                    m_flex.AutoSizeRows();
                    m_flex.AutoSizeCols();
                }
                else
                {
                    dt.Clear();
                }
            }
            else
            {
                InitDal dal = new InitDal();
                dt = dal.GetIninitEmptyDatable();
                m_flex.DataSource = dt;
                m_flex.AutoSizeRows();
                m_flex.AutoSizeCols();
            }

            DataRow dr = dt.NewRow();
            foreach (DataColumn dc in dt.Columns)
            {
                if(dc.ColumnName.Contains("J"))
                    dr[dc.ColumnName] = 10;
                else
                    dr[dc.ColumnName] = 0;
            }
            dt.Rows.Add(dr);
            for (int r = 1; r < m_flex.Rows.Count; r++)
            {
                m_flex[r, 0] = r;
            }
        }
    }
}
